<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!-- 查询 -->
        <el-form ref="orderData" :model="orderData" size="small" :inline="true" label-width="68px">
          <el-form-item label="基地规格">
            <el-select v-model="spaceName" placeholder="请选择基地规格" @change="onChange" @focus="focus">
              <el-option v-for="item in spaceNameList" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间规格">
            <el-select v-model="spaceType" placeholder="请选择房间规格" :disabled="selected" @change="change">
              <el-option v-for="item in spaceTypeList" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间名称">
            <el-input v-model="orderData.roomName" placeholder="请输入房间名称" />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="orderStatus" placeholder="请选择订单状态" @change='changeOrder'>
              <el-option v-for="item in orderType" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择时间">
            <el-date-picker v-model="tiemValue" type="daterange" value-format="yyyy-MM-dd" range-separator="--"
              start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"
              @change="changeTime">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitsear" icon="el-icon-search" size="mini">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 数据统计 -->
        <el-form class="orderStatistics" ref="orderStatistics" :model="orderStatistics" size="small" :inline="true">
          <download-excel class="export-excel-wrapper" :fetch="createExportData" header="订单数据统计" :data="dataList">
            <el-button type="warning" plain icon="el-icon-download"> 导出 </el-button>
          </download-excel>
          <div>
            <el-form-item label="订单数量" style="margin-right:30px">
              <el-tag size="medium" type="success">{{orderStatistics.orderNum}} /条</el-tag>
            </el-form-item>
            <el-form-item label="实际总收入" style="margin-right:30px">
              <el-tag size="medium" type="danger">{{orderStatistics.orderPrice}} /元</el-tag>
            </el-form-item>
            <el-form-item label="支付金额" style="margin-right:30px">
              <el-tag size="medium" type="warning">{{orderStatistics.orderSucc}} /元</el-tag>
            </el-form-item>
            <el-form-item label="退款金额" style="margin-right:30px">
              <el-tag size="medium" type="danger">{{orderStatistics.orderRefund}} /元</el-tag>
            </el-form-item>
          </div>
        </el-form>
        <!-- 订单列表 -->
        <el-table v-loading="loading" :data="tableData" ref="tableRef" border style="width: 100%" class="mb20">
          <el-table-column prop="capsuleInfoTitle" label="项目" align="center" width="240">
          </el-table-column>
          <el-table-column prop="roomName" label="房间" align="center" width="140">
          </el-table-column>
          <!-- <el-table-column prop="din" label="编号" align="center" width="90">
          </el-table-column> -->
          <el-table-column prop="orderNo" label="订单号" align="center" width="240">
          </el-table-column>
          <!-- <el-table-column prop="payOrderId" label="订单ID" align="center" width="80">
          </el-table-column> -->
          <el-table-column prop="payRealPrice" label="订单金额" align="center" width="120">
            <template slot-scope="scope">
              <div style="color: #e45656;">{{scope.row.payRealPrice}}元</div>
            </template>
          </el-table-column>
          <el-table-column prop="otherPayOrderNo" label="第三方支付单号" align="center" width="190">
          </el-table-column>
          <el-table-column prop="preOrderTime" label="下单时间" align="center" width="160">
          </el-table-column>
          <el-table-column prop="checkInTime" label="入住时间" align="center" width="160">
          </el-table-column>
          <el-table-column prop="checkOutTime" label="退房时间" align="center" width="160">
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" align="center" width="150">
            <template slot-scope="scope">
              <div class="test">
                <div class="roomStatus" style=" padding: 4px 8px;"
                  :style="{background:scope.row.orderStatus == 0 ? '#5ac725' : (scope.row.orderStatus == 1 ? '#f56c6c' : (scope.row.orderStatus == '2' ? '#f9ae3d' : (scope.row.orderStatus == '3' ? '#909399' :'')))}">
                  {{scope.row.orderStatus == 0 ? '下单' : (scope.row.orderStatus == 1 ? '已支付' : (scope.row.orderStatus == '2' ? '已退款' : (scope.row.orderStatus == '3' ? '已取消' :'')))}}
                </div>
               <div class="s"
                  v-if="scope.row.orderStatus == 1 && scope.row.roomStatus != 4 && scope.row.roomStatus != 0"
                  @click.stop="onRefund(scope.row.payOrderId , scope.row.payRealPrice)">去退款</div>
                <div class="s h"
                  v-if="scope.row.orderStatus == 1 && scope.row.roomStatus != 4 && scope.row.roomStatus != 0"
                  @click.stop="onChangeHous(scope.row.capsuleRoomId,scope.row.payOrderId)">
                  去换房</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="useRoomStatus" label="房间状态" align="center" width="90">
            <template slot-scope="scope">
             <!-- <div class="roomStatus"
                :style="{color:scope.row.roomStatus == 0 ? '#5ac725' : (scope.row.roomStatus == 1 ? '#f56c6c' : (scope.row.roomStatus == '2' ? '#f9ae3d' : (scope.row.roomStatus == '3' ? '#909399' :(scope.row.roomStatus == '4' ? '#f9ae3d' : '#16a951'))))}">
                {{scope.row.roomStatus == 0 ? '空闲' : (scope.row.roomStatus == 1 ? '入住中' : (scope.row.roomStatus == '2' ? '维修' : (scope.row.roomStatus == '3' ? '已下线' :(scope.row.roomStatus == '4' ? '保洁' : '待入住'))))}}
              </div> -->
              <div class="roomStatus" :style="{color:scope.row.useRoomStatus == 0 ? '#f56c6c' : '#5ac725'}">
                {{scope.row.useRoomStatus == 0 ? '使用中' : '未使用'}}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-document"
                @click.stop="spaceRoomDetail(scope.row.payOrderId)">详情</el-button>

              <!-- <el-button size="mini" type="text" icon="el-icon-edit"
                @click.stop="spaceRoomDetail(scope.row.id , types = 'edit')">编辑</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row.id)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background align='right' @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="orderData.pageNum" :page-size="orderData.pageSize" layout="prev, pager, next" :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <!-- 详情 -->
    <el-dialog title="订单详情" :visible.sync="orderVisibles" width="54%" :before-close="handleClose">
      <el-form ref="orderDetail" :model="orderDetail" label-width="120px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="基地ID" prop="capsuleInfoId">
              <el-input v-model="orderDetail.capsuleInfoId" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="基地名称" prop="capsuleInfoTitle">
              <el-input v-model="orderDetail.capsuleInfoTitle" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房间规格ID" prop="capsuleSpecsId">
              <el-input v-model="orderDetail.capsuleSpecsId" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房间规格名称" prop="capsuleSpecsName">
              <el-input v-model="orderDetail.capsuleSpecsName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房间名称" prop="roomName">
              <el-input v-model="orderDetail.roomName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="用户" prop="checkInRealName">
              <el-input v-model="orderDetail.checkInRealName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="身份证" prop="checkInIdCard">
              <el-input v-model="orderDetail.checkInIdCard" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="手机号" prop="checkInPhone">
              <el-input v-model="orderDetail.checkInPhone" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="入住时间" prop="checkInTime">
              <el-input v-model="orderDetail.checkInTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="退房时间" prop="checkOutTime">
              <el-input v-model="orderDetail.checkOutTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房间编号" prop="din">
              <el-input v-model="orderDetail.din" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="orderDetail.orderNo" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-input v-model="orderDetail.orderStatus" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="第三方支付单号" prop="otherPayOrderNo">
              <el-input v-model="orderDetail.otherPayOrderNo" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单ID" prop="payOrderId">
              <el-input v-model="orderDetail.payOrderId" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单金额" prop="payRealPrice">
              <el-input v-model="orderDetail.payRealPrice" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="下单时间" prop="preOrderTime">
              <el-input v-model="orderDetail.preOrderTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="是否改过价" prop="roomChangeStatus">
              <el-input v-model="orderDetail.roomChangeStatus" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房间状态" prop="roomStatus">
              <el-input v-model="roomStatus" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="房间图片" prop="roomImgs">
              <template slot-scope="scope">
                <div class="img">
                  <img v-for="(item , index) in orderDetail.roomImgs" :key="index" :src="item.url" />
                </div>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="orderVisibles = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 退款 -->
    <el-dialog title="退款" :visible.sync="refundVisibles" width="44%" :before-close="refundClose">
      <el-form ref="refundForm" :model="refundForm" label-width="120px" :rules="rules">
        <el-row>
          <el-col :span="22">
            <el-form-item label="退款金额" prop="refundPrice">
              <span style="color: #e45656;">当前可退金额：￥{{price}} 元</span>
              <el-input type="number" v-model="refundForm.refundPrice" placeholder="输入退款金额" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="退款理由" prop="refundReason">
              <el-input type="textarea" v-model="refundForm.refundReason" placeholder="输入退款理由" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer">
        <el-button @click="refundVisibles = false">取 消</el-button>
        <el-button type="primary" @click="onRefundForm('refundForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 换房 -->
    <el-dialog title="换房" :visible.sync="changeHousVisibles" width="30%">
      <el-form ref="changeHousForm" :model="changeHousForm" label-width="120px" :rules="housRules">
        <el-row>
          <el-col :span="14">
            <el-form-item label="请选择房间" prop="exchangeRoomId">
              <el-select ref="selectRoom" clearable v-model="changeHousForm.exchangeRoomId" placeholder="请选择可更换的房间">
                <el-option v-for="(item ,index) in spaceRoomList" :key="index" :label="item.roomName"
                  :value="item.capsuleRoomId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="换房原因" prop="reason">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" v-model="changeHousForm.reason"
                placeholder="输入换房理由" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer">
        <el-button @click="changeHousVisibles = false">取 消</el-button>
        <el-button type="primary" @click="onChangeHousForm('changeHousForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getOrderList,
    getRoomList,
    getSpaceroom,
    getRoomDetail,
    refundOrder,
    spaceTypeSelect,
    houseList,
    onExchangeRoom,
    conditionOrder,
    getExcelOrder
  } from "@/api/order/order"
  export default {
    data() {
      return {
        loading: true,
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        orderData: {
          "createBeginTime": "", //订单开始时间:yyyy-MM-dd
          "createEndTime": "", //订单结束时间:yyyy-MM-dd
          "orderStatus": 99,
          "pageNum": 1, //页码
          "pageSize": 10, //条数
          "payType": "", //支付方式
          "roomName": "" //太空舱房间名称
        },
        tableData: [],
        spaceNameList: [],
        spaceTypeList: [],
        spaceName: '',
        spaceType: '',
        orderStatus: '',
        orderType: [{
            value: 0,
            label: '下单'
          },
          {
            value: 1,
            label: '已支付'
          },
          {
            value: 2,
            label: '已退款'
          },
          {
            value: 3,
            label: '已取消'
          }
        ],
        tiemValue: '',
        selected: true,
        orderVisibles: false,
        orderDetail: {},
        roomStatus: '',
        refundVisibles: false,
        refundForm: {},
        price: 0,
        rules: {
          refundPrice: [{
            required: true,
            message: '请输入退款金额',
            trigger: 'blur'
          }],
          refundReason: [{
            required: true,
            message: '请输入退款理由',
            trigger: 'blur'
          }]
        },
        housRules: {
          capsuleRoomId: [{
            required: true,
            message: '请选择可换房的房间',
            trigger: 'blur'
          }],
          reason: [{
            required: true,
            message: '请输入换房原因',
            trigger: 'blur'
          }],
        },
        changeHousVisibles: false,
        changeHousForm: {},
        spaceRoomList: [],
        orderStatistics: {
          orderNum: '',
          orderPrice: '',
          orderSucc: '',
          orderRefund: ''
        },
        dataList: [],
        flag: false
      }
    },
    created() {
      this.getOrderList()
      // 获取基地规格
      getRoomList().then(res => {
        this.spaceNameList = res.data
      })
    },
    methods: {
      getOrderList() {
        // this.orderData.pageNum = this.queryParams.pageNum
        // this.orderData.pageSize = this.queryParams.pageSize
        getOrderList(this.orderData).then(res => {
          this.loading = false
          this.tableData = res.data.rows
          this.total = res.data.total
          conditionOrder(this.orderData).then(res => {
            this.orderStatistics = {
              orderNum: res.data.cntA,
              orderPrice: res.data.sumA,
              orderSucc: res.data.sumB,
              orderRefund: res.data.sumC,
            }
          })
          if (this.flag) {
            if (this.tableData.length > 0) {
              this.getExcelOrder()
            } else {
              this.$message({
                message: '暂无数据！',
                type: 'warning'
              })
            }
          }
        })
      },
      handleSizeChange(val) {
        this.orderData.pageNum = val
        this.getOrderList()
      },
      handleCurrentChange(val) {
        this.orderData.pageNum = val
        this.getOrderList()
      },
      focus() {
        this.spaceTypeList = []
      },
      onChange(e) {
        this.spaceType = ''
        if (this.spaceNameList.length > 0) {
          this.spaceNameList.map(item => {
            if (e == item.value) {
              this.spaceName = item.label
              this.orderData.capsuleInfoId = item.value
            }
          })
        }
        getSpaceroom(e).then(res => {
          this.spaceTypeList = res.data
          this.selected = false
        })
      },
      change(e) {
        if (this.spaceTypeList.length > 0) {
          this.spaceTypeList.map(item => {
            if (e == item.value) {
              this.spaceType = item.label
              this.orderData.capsuleSpecsId = item.value
            }
          })
        }
      },
      changeTime() {
        this.orderData.createBeginTime = this.tiemValue[0]
        this.orderData.createEndTime = this.tiemValue[1]
      },
      changeOrder(e) {
        this.orderData.orderStatus = e
      },
      spaceRoomDetail(id) {
        getRoomDetail(id).then(res => {
          // console.log("res----->", res)
          this.orderVisibles = true
          res.data.roomImgs = JSON.parse(res.data.roomImgs)
          this.orderDetail = res.data
          this.orderType.map(item => {
            if (this.orderDetail.orderStatus == item.value) {
              this.orderDetail.orderStatus = item.label
            }
          })
          if (this.orderDetail.roomStatus == 0) {
            this.roomStatus = '空闲'
          } else if (this.orderDetail.roomStatus == 1) {
            this.roomStatus = '入住中'
          } else if (this.orderDetail.roomStatus == 2) {
            this.roomStatus = '维修'
          } else if (this.orderDetail.roomStatus == 3) {
            this.roomStatus = '已下线'
          } else if (this.orderDetail.roomStatus == 4) {
            this.roomStatus = '保洁'
          } else {
            this.roomStatus = '预定'
          }
        })

      },
      onSubmitsear() {
        this.getOrderList()
      },
      resetQuery() {
        this.orderData = {
          "createBeginTime": "",
          "createEndTime": "",
          "orderStatus": 99,
          "pageNum": 1,
          "pageSize": 10,
          "payType": "",
          "roomName": ""
        }
        this.spaceType = ''
        this.spaceName = ''
        this.selected = true
        this.flag = false
        this.getOrderList()
      },
      handleClose() {
        this.orderVisibles = false
      },
      refundClose() {
        this.refundVisibles = false
      },
      onRefund(orderId, price) {
        // console.log(orderId, price)
        this.price = price
        this.refundForm.payOrderId = orderId
        this.refundVisibles = true
      },
      // 换房
      onChangeHous(roomId, capsulePayOrderId) {
        // 基地房间规格查询
        houseList(roomId).then(res => {
          // console.log("spaceTypeSelect", res)
          if (res.code == 200) {
            this.spaceRoomList = res.data
            this.changeHousForm.capsulePayOrderId = capsulePayOrderId
            this.changeHousForm.capsuleRoomId = +roomId
            this.changeHousVisibles = true
          }
        })
      },
      // 确定换房
      onChangeHousForm(changeHousForm) {
        this.$refs[changeHousForm].validate((valid) => {
          if (valid) {
            this.$confirm('确定换房吗?', '提示', {
              confirmButtonText: '确 定',
              cancelButtonText: '取 消',
              type: 'warning'
            }).then(() => {
              // console.log(this.changeHousForm)
              onExchangeRoom(this.changeHousForm).then(res => {
                if (res.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '换房成功！'
                  })
                }
                this.changeHousVisibles = false
              })
            })
          }
        })
      },
      onRefundForm(refundForm) {
        this.$refs[refundForm].validate((valid) => {
          if (valid) {
            if (Number(this.refundForm.refundPrice) > Number(this.price)) return this.$message({
              type: 'error',
              message: '退款金额不得大于支付金额！'
            })
            if (this.refundForm.refundPrice == 0 || this.refundForm.refundPrice < 0) return this.$message({
              type: 'warning',
              message: '退款金额需大于0'
            })
            this.$confirm('您是否确定退款吗?', '提示', {
              confirmButtonText: '确 定',
              cancelButtonText: '取 消',
              type: 'warning'
            }).then(() => {
              this.refundVisibles = false
              this.refundOrder()
              this.refundForm = {}
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
          }
        })
      },
      refundOrder() {
        refundOrder(this.refundForm).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.data
            })
            this.refundVisibles = false
            this.getOrderList()
          }
        })
      },
      // 导出
      createExportData() {
        this.flag = true
        this.getOrderList()
      },
      async getExcelOrder() {
        let parmas = {
          beginTime: this.orderData.createBeginTime,
          capsuleInfoId: this.orderData.capsuleInfoId,
          endTime: this.orderData.createEndTime,
          orderStatus: this.orderData.orderStatus
        }
        let data = await getExcelOrder(parmas)
        // console.log('data---->',data)
        const fileReader = new FileReader()
        fileReader.readAsDataURL(data)
        fileReader.onload = (event) => {
          let a = document.createElement('a')
          a.download = `订单数据报表_${new Date().getTime()}.xlsx`
          a.href = event.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      }
    }
  }
</script>

<style lang="scss">
  .test {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .s {
      padding: 4px 8px;
      font-size: 12px;
      border-radius: 2px;
      color: #fff;
      background: #3c9cff;
      cursor: pointer;
    }

    .h {
      background: #f9ae3d !important;
    }
  }

  .roomStatus {
    color: #fff;
    border-radius: 2px;
    font-size: 12px;
    // padding: 4px 8px;
  }

  .img {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    img {
      width: 80px;
      height: 80px;
      margin-right: 6px;
    }
  }

  .el-tag {
    font-size: 16px;
  }

  .orderStatistics {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>
